package com.zretc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.google.gson.Gson;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet2")
@MultipartConfig
public class UploadServlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("application/json;charset=utf-8");
		// 0 请求编码，如果过滤器已经设置，这里可以省略
		// 1获取用户名
		String username = request.getParameter("username");
		System.out.println("username :" + username);
		// 2 获取上传文件
		// javax.servlet.http.Part
		Part file = request.getPart("file");
		// 调用方法实现上传
		// fileName 参数fileName上传的目标位置是哪里？
		// 3 包含完整的路径名+文件名
		String pathString = request.getRealPath("/imgs/");
		pathString += file.getSubmittedFileName();
		System.out.println("pathString  :" + pathString);
		// 4 写入目标位置
		file.write(pathString);

		PrintWriter out = response.getWriter();
		Map map = new HashMap<String, Object>();
		map.put("msg", "ok");
		map.put("code", 200);
		Gson gson = new Gson();
		out.print(gson.toJson(map));

	}

}
